package com.github.catvod.spider;

import android.annotation.SuppressLint;
import android.content.Context;

import com.github.catvod.bean.Class;
import com.github.catvod.bean.Result;
import com.github.catvod.bean.Vod;
import com.github.catvod.crawler.Spider;
import com.github.catvod.net.OkHttp;
import com.github.catvod.utils.Json;
import com.github.catvod.utils.Notify;
import com.github.catvod.utils.Util;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 色虎视频飞机永久地址:sehuav.cc
 */
public class SexTiger extends Spider {
    private static String siteUrl="https://1.sehu734.cc:8888/";

    // 获取从请求头
    private Map<String, String> getHeader() {
        Map<String, String> header = new HashMap<>();
        header.put("User-Agent", Util.CHROME);
        header.put("accept-language", "zh-CN,zh;q=0.9");
        header.put("sec-fetch-mode", "cors");
        return header;
    }

    /**
     * 匹配网页html
     * @param html
     * @return
     */
    private String find(String html) {
        String regex = "<script>document.write\\(decodeURIComponent\\((.*)\\)\\)</script>";
        Pattern pattern = Pattern.compile(regex);
        Matcher m = pattern.matcher(html);
        return m.find() ? URLDecoder.decode(m.group(1)).trim() : "";
    }

    @Override
    public void init(Context context) throws Exception {
        Document doc = Jsoup.parse(find(OkHttp.string(siteUrl, getHeader())));
        if (!doc.select("div.enter-maomi").isEmpty()){
            siteUrl=find_filed(doc);
            Notify.show("枫斗~虎虎自动换源~");
        }
        super.init(context);
    }

    private String find_filed(Document doc) {
        return doc.select("#as").attr("href");
    }


    @Override
    public String homeContent(boolean filter) throws Exception {
        Document doc = Jsoup.parse(find(OkHttp.string(siteUrl, getHeader())));
        // 进行获取导航
        Elements a_category = doc.select("div.s-main-box").first().nextElementSibling().select("a");
        List<Class> classes = new ArrayList<>();
        for (Element a : a_category) {
            String type_id = a.attr("href");
            String type_name = a.text();
            classes.add(new Class(type_id, type_name));
        }
        List<Vod> list= parseVod(doc);
        return Result.string(classes, list);
    }

    // 将秒数转换为 HH:MM:SS 格式
    @SuppressLint("DefaultLocale")
    public static String secondsToHMS(int seconds) {
        int hours = seconds / 3600;
        int remainingSeconds = seconds % 3600;
        int minutes = remainingSeconds / 60;
        int finalSeconds = remainingSeconds % 60;
        return String.format("%02d:%02d:%02d", hours, minutes, finalSeconds);
    }

    private List<Vod> parseVod(Document doc) {
        List<Vod> list = new ArrayList<>();
        Elements listbox=doc.select("div.ran-box.vod-list");
        for (Element item : listbox) {
            // 进行获取到所有的子元素
            Elements childrenDiv = item.children();
            for (Element voc : childrenDiv) {
                if (!voc.select("div.item-title-box").isEmpty())continue;
                // 进行跳过广告
                if(!voc.select("div.abk-item").isEmpty())continue;
                String url = voc.select("a").attr("href");
                String pic = voc.select("div.rank-a > img").attr("data-original");
                Pattern pattern = Pattern.compile("<script>document.write\\(secondsToHMS\\((.*)\\)\\)</script>");
                Matcher matcher = pattern.matcher(voc.toString());
                String time = matcher.find() ? matcher.group(1) : "";
                String remark = null;
                if (time != null) {
                    remark = secondsToHMS(Integer.parseInt(time));
                }
                String name = voc.select("div.rank-title").text();
                list.add(new Vod(url, name, pic, remark));
            }
        }
        return list;
    }

    @Override
    public String categoryContent(String tid, String pg, boolean filter, HashMap<String, String> extend) throws Exception {
        if (tid.equals("/")){
            return Result.string(parseVod(Jsoup.parse(find(OkHttp.string(siteUrl, getHeader())))));
        }
        String categoryUrl;
        if (siteUrl.endsWith("/")){
            categoryUrl= Util.removeUrlTrailingSlash(siteUrl)+tid+"/"+pg+"/";
        }else {
            categoryUrl= siteUrl+tid+"/"+pg+"/";
        }
        String str_html = find(OkHttp.string(categoryUrl, getHeader()));
        Document doc = Jsoup.parse(str_html);
        List<Vod> list = parseVod(doc);
        Integer total = (Integer.parseInt(pg) + 1) * 30;
        return Result.string(Integer.parseInt(pg), Integer.parseInt(pg) + 1, 10, total, list);
    }

    @Override
    public String detailContent(List<String> ids) throws Exception {
        String vodId = ids.get(0);
        String detailURl= siteUrl.endsWith("/")?Util.removeUrlTrailingSlash(siteUrl)+vodId:siteUrl+vodId;
        String html = find(OkHttp.string(detailURl, getHeader()));
        Pattern patternMau8 = Pattern.compile("var url = \"(.*)\";");
        Pattern patternPic = Pattern.compile("var poster = \"(.*)\";");
        Matcher matcherM3u8 = patternMau8.matcher(html);
        Matcher matcherPic = patternPic.matcher(html);
        String m3u8 = matcherM3u8.find() ? matcherM3u8.group(1) : "";
        String pic = matcherPic.find() ? matcherPic.group(1) : "";
        String title = Jsoup.parse(html).select("div.video-title").text();
        Vod vod = new Vod();
        vod.setVodId(vodId);
        vod.setVodPic(pic);
        vod.setVodName(title);
        vod.setVodPlayUrl("播放$"+m3u8);
        vod.setVodPlayFrom("m3u8");
        return Result.string(vod);
    }

    @Override
    public String playerContent(String flag, String id, List<String> vipFlags) throws Exception {
        return Result.get().url(id).header(getHeader()).string();
    }

    @Override
    public String searchContent(String key, boolean quick) throws Exception {
        String searchUrl=siteUrl+"search/"+key;
        String html = find(OkHttp.string(searchUrl, getHeader()));
        Document doc = Jsoup.parse(html);
        List<Vod> list = parseVod(doc);
        return Result.string(list);
    }
}
